package com.extension.company.view.home.hotactivity;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.extension.company.admin.R;
import com.extension.company.common.mvp.BaseFragment;
import com.extension.company.contract.home.GoodInfoFragmentContract;
import com.extension.company.model.entity.GoodsInfoDetail2;
import com.extension.company.model.entity.GoodsInforBean;
import com.extension.company.presenter.home.GoodInfoFragmentPresenter;
import com.extension.company.view.details.SecondFloorTroubleFragment;
import com.extension.company.view.details.SecondFloorFragment;
import com.extension.company.view.details.RecommendGoodsBean;
import com.extension.company.common.widget.flowLayout.FlowLayout;
import com.extension.company.common.widget.flowLayout.TagAdapter;
import com.extension.company.common.widget.flowLayout.TagFlowLayout;
import com.extension.company.common.widget.SlideDetailsLayout;
import com.gxz.PagerSlidingTabStrip;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * item页ViewPager里的商品Fragment,推广的商品页
 */
public class PopularizeGoodsInfoFragment extends BaseFragment<GoodInfoFragmentContract.View, GoodInfoFragmentPresenter> implements GoodInfoFragmentContract.View, View.OnClickListener, SlideDetailsLayout.OnSlideDetailsListener {

	private PagerSlidingTabStrip psts_tabs;
	private SlideDetailsLayout sv_switch;
	private ScrollView sv_goods_info;
	private FloatingActionButton fab_up_slide;
	public ConvenientBanner vp_item_goods_img, vp_recommend;
	private LinearLayout ll_goods_detail, ll_goods_config;
	private TextView tv_goods_detail, tv_goods_config;
	private View v_tab_cursor;
	public FrameLayout fl_content;
	public LinearLayout ll_current_goods, ll_activity, ll_comment, ll_recommend, ll_pull_up;
	public TextView tv_goods_title, tv_new_price, tv_old_price, tv_current_goods, tv_comment_count, tv_good_comment;
	public TextView immediatelyShare;
	private TextView recommend;
	@BindView(R.id.btn_buy_or_order)
	TextView btnBuyOrOrder;


	/**
	 * 当前商品详情数据页的索引分别是图文详情、规格参数
	 */
	private int nowIndex;
	private float fromX;
	public SecondFloorTroubleFragment secondFloorTroubleFragment;
	public SecondFloorFragment secondFloorFragment;
	private Fragment nowFragment;
	private List<TextView> tabTextList;
	private List<Fragment> fragmentList = new ArrayList<>();
	private FragmentTransaction fragmentTransaction;
	private FragmentManager fragmentManager;
	public HotEventTopPopularizeActivity activity;
	private LayoutInflater inflater;
	private int type;

	private SHARE_MEDIA[] copyTransmitShare = {
			SHARE_MEDIA.SINA,
			SHARE_MEDIA.QQ,
			SHARE_MEDIA.WEIXIN,
			SHARE_MEDIA.QZONE,
			SHARE_MEDIA.WEIXIN_CIRCLE
	};

	@Override
	public void onAttach(Context context) {
		super.onAttach(context);
		this.activity = (HotEventTopPopularizeActivity) context;
	}

	// 开始自动翻页
	@Override
	public void onResume() {
		super.onResume();
		//开始自动翻页，banner设置
		vp_item_goods_img.startTurning(4000);
	}

	// 停止自动翻页，banner设置
	@Override
	public void onPause() {
		super.onPause();
		//停止翻页
		vp_item_goods_img.stopTurning();
	}

	@Override
	public GoodInfoFragmentContract.View createView() {
		return this;
	}

	@Override
	public GoodInfoFragmentPresenter createPresenter() {
		return new GoodInfoFragmentPresenter();
	}

//	@Nullable
//	@Override
//	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//		this.inflater = inflater;
//		View rootView = inflater.inflate(R.layout.fragment_goods_info, null);
//		initView(rootView);
//		initListener();
//		initData();
//		return rootView;
//	}

	@Override
	public int getMainLayout() {
		return R.layout.fragment_popularize_goods_info;
	}

	@Override
	public void init() {
		type = getArguments().getInt("type");
		Log.d("zwk", "获取到的类型" + type);
		initView();
		initData();
		initListener();
	}

	private void initListener() {
		fab_up_slide.setOnClickListener(this);
		ll_current_goods.setOnClickListener(this);
		ll_comment.setOnClickListener(this);
		ll_pull_up.setOnClickListener(this);
		ll_goods_detail.setOnClickListener(this);
		ll_goods_config.setOnClickListener(this);
		sv_switch.setOnSlideDetailsListener(this);
		immediatelyShare.setOnClickListener(this);
		recommend.setOnClickListener(this);
	}

	private void initView() {
		psts_tabs = (PagerSlidingTabStrip) getViewById(R.id.psts_tabs); // 标题栏左右滑动的tab
		fab_up_slide = (FloatingActionButton) getViewById(R.id.fab_up_slide); // 底部的floatButton
		sv_switch = (SlideDetailsLayout) getViewById(R.id.sv_switch);        //左右滑动的tab的布局
		sv_goods_info = (ScrollView) getViewById(R.id.sv_goods_info);     // tab布局中scrollview
		v_tab_cursor = getViewById(R.id.v_tab_cursor);                    // 商品详情第二个界面的fragment 中的tab 底部的横线
		vp_item_goods_img = (ConvenientBanner) getViewById(R.id.vp_item_goods_img);  // banner

		fl_content = (FrameLayout) getViewById(R.id.fl_content);           // 商品详情第二个fragment的content容器
		ll_current_goods = (LinearLayout) getViewById(R.id.ll_current_goods);  // 请选择套餐

		ll_comment = (LinearLayout) getViewById(R.id.ll_comment);
		ll_recommend = (LinearLayout) getViewById(R.id.ll_recommend);
		ll_pull_up = (LinearLayout) getViewById(R.id.ll_pull_up);   // 上拉效果，弹出第二个fragment
		ll_goods_detail = (LinearLayout) getViewById(R.id.ll_goods_detail); //商品行情
		ll_goods_config = (LinearLayout) getViewById(R.id.ll_goods_config); // 评论
		tv_goods_detail = (TextView) getViewById(R.id.tv_goods_detail); // 商品详情
		tv_goods_config = (TextView) getViewById(R.id.tv_goods_config); // 商品评论
		tv_goods_title = (TextView) getViewById(R.id.tv_goods_title);
		tv_new_price = (TextView) getViewById(R.id.tv_new_price);  // 现价
		tv_old_price = (TextView) getViewById(R.id.tv_old_price);   // 原价
		tv_current_goods = (TextView) getViewById(R.id.tv_current_goods);  // x选择套餐
		tv_comment_count = (TextView) getViewById(R.id.tv_comment_count);
		tv_good_comment = (TextView) getViewById(R.id.tv_good_comment);
		immediatelyShare = getViewById(R.id.immediately_share);
		recommend = getViewById(R.id.btn_my_recommend);
		setDetailData();
		setLoopView();
//		setRecommendGoods();

		//设置文字中间一条横线
		tv_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
		fab_up_slide.hide();

		//设置指示器 /指示器的排列顺序
		vp_item_goods_img.setPageIndicator(new int[]{R.drawable.index_white, R.drawable.index_red});
		vp_item_goods_img.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);

//        vp_recommend.setPageIndicator(new int[]{R.drawable.shape_item_index_white, R.drawable.shape_item_index_red});
//        vp_recommend.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL);
	}

	private void initData() {
		fragmentList = new ArrayList<>();
		tabTextList = new ArrayList<>();
		tabTextList.add(tv_goods_detail);
		tabTextList.add(tv_goods_config);
	}

	/**
	 * 加载完商品详情执行
	 */
	public void setDetailData() {
		if (type == 0) {
			btnBuyOrOrder.setText("立即预约");
		} else {
			btnBuyOrOrder.setText("立即购买");
		}

		secondFloorTroubleFragment = new SecondFloorTroubleFragment(); //评论fragment
		secondFloorFragment = new SecondFloorFragment(); // 商品详情页第二页

		fragmentList.add(secondFloorTroubleFragment);
		fragmentList.add(secondFloorFragment);

		nowFragment = secondFloorFragment;  // 当前fragment
		fragmentManager = getChildFragmentManager();  // fragment中的子fragment的管理者
		//默认显示商品详情tab，第二个商品详情界面
		fragmentManager.beginTransaction().replace(R.id.fl_content, nowFragment).commitAllowingStateLoss();
	}

	/**
	 * 设置推荐商品
	 */
//	public void setRecommendGoods() {
//		List<RecommendGoodsBean> data = new ArrayList<>();
//		data.add(new RecommendGoodsBean("Letv/乐视 LETV体感-超级枪王 乐视TV超级电视产品玩具 体感游戏枪 电玩道具 黑色",
//				"http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg", new BigDecimal(599), "799"));
//		data.add(new RecommendGoodsBean("IPEGA/艾派格 幽灵之子 无线蓝牙游戏枪 游戏体感枪 苹果安卓智能游戏手柄 标配",
//				"http://img2.hqbcdn.com/product/00/76/0076cedb0a7d728ec1c8ec149cff0d16.jpg", new BigDecimal(299), "399"));
//		data.add(new RecommendGoodsBean("Letv/乐视 LETV体感-超级枪王 乐视TV超级电视产品玩具 体感游戏枪 电玩道具 黑色",
//				"http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg", new BigDecimal(599), "799"));
//		data.add(new RecommendGoodsBean("IPEGA/艾派格 幽灵之子 无线蓝牙游戏枪 游戏体感枪 苹果安卓智能游戏手柄 标配",
//				"http://img2.hqbcdn.com/product/00/76/0076cedb0a7d728ec1c8ec149cff0d16.jpg", new BigDecimal(299), "399"));
//		List<List<RecommendGoodsBean>> handledData = handleRecommendGoods(data);
	//设置如果只有一组数据时不能滑动
//        vp_recommend.setManualPageable(handledData.size() == 1 ? false : true);
//        vp_recommend.setCanLoop(handledData.size() == 1 ? false : true);
//        vp_recommend.setPages(new CBViewHolderCreator() {
//            @Override
//            public Object createHolder() {
//                return new ItemRecommendAdapter();
//            }
//        }, handledData);
//	}
	@Override
	public void onClick(final View v) {
		switch (v.getId()) {
			case R.id.ll_pull_up:
				//上拉查看图文详情
				sv_switch.smoothOpen(true);
				break;

			case R.id.fab_up_slide:
				//点击滑动到顶部
				sv_goods_info.smoothScrollTo(0, 0);
				sv_switch.smoothClose(true);
				break;

			case R.id.ll_goods_detail:
				//商品详情tab
				nowIndex = 0;
				scrollCursor();
				switchFragment(nowFragment, secondFloorFragment);
				nowFragment = secondFloorFragment;
				break;

			case R.id.ll_goods_config:
				//规格参数tab
				nowIndex = 1;
				scrollCursor();
				switchFragment(nowFragment, secondFloorTroubleFragment);
				nowFragment = secondFloorTroubleFragment;
				break;
			case R.id.immediately_share:
				ShareAction share = new ShareAction(activity)
						.setDisplayList(copyTransmitShare)                 // 设置分享面板的内容
						.setShareboardclickCallback(new ShareBoardlistener() {  // 分享面板设置点击监听
							@Override
							public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {

								UMWeb web = new UMWeb("http://mobile.umeng.com/social");
								web.setTitle("来自分享面板标题");
								web.setDescription("来自分享面板内容");
								web.setThumb(new UMImage(activity, R.drawable.xiaomi));
								new ShareAction(activity).withMedia(web)
										.setPlatform(share_media)
										.setCallback(new UMShareListener() {
											@Override
											public void onStart(SHARE_MEDIA share_media) {

											}

											@Override
											public void onResult(SHARE_MEDIA share_media) {

											}

											@Override
											public void onError(SHARE_MEDIA share_media, Throwable throwable) {

											}

											@Override
											public void onCancel(SHARE_MEDIA share_media) {

											}
										})
										.share();
							}
						});
				share.open();
				break;

			case R.id.btn_my_recommend:
				// 点击打开popWindow 界面
				View view = LayoutInflater.from(activity).inflate(R.layout.popwindow_recommend, null);
				ImageView dismissImg = view.findViewById(R.id.windowpopmenu_dismiss);
				final TextView introduct=view.findViewById(R.id.commodity_introduce);

				final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
				popupWindow.setAnimationStyle(R.style.popwindow_anim_style);
				popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

				WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
				lp.alpha = 0.7f;
				activity.getWindow().setAttributes(lp);

				popupWindow.setFocusable(true);
				popupWindow.setOutsideTouchable(true);
				popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

				popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
					@Override
					public void onDismiss() {
						WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
						lp.alpha = 1.0f;
						activity.getWindow().setAttributes(lp);
					}
				});

				final TagFlowLayout specificationTagFlowLayout = view.findViewById(R.id.specifaction);

				final List<String> specitionList = new ArrayList<>();
				specitionList.add("item1item1item1item1item1item1item1item");
				specitionList.add("item2");
				TagAdapter<String> specitionTagAdapter = new TagAdapter<String>(specitionList) {
					@Override
					public View getView(FlowLayout parent, int position, String s) {
						TextView historyContent = (TextView) LayoutInflater.from(activity).inflate(R.layout.popwindow_tabflow_item, specificationTagFlowLayout, false);
						historyContent.setText(s);
						return historyContent;
					}
				};
				specificationTagFlowLayout.setAdapter(specitionTagAdapter);


				dismissImg.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						popupWindow.dismiss();
						WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
						lp.alpha = 1.0f;
						activity.getWindow().setAttributes(lp);
					}
				});

				specificationTagFlowLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
					@Override
					public boolean onTagClick(View view, int position, FlowLayout parent) {
						Log.d("zwk","点击了"+position+"内容"+specitionList.get(position));
						introduct.setText(specitionList.get(position));
						return false;
					}
				});
				break;
			default:
				break;
		}
	}

	/**
	 * 给商品轮播图设置图片路径
	 */
	public void setLoopView() {
		List<String> imgUrls = new ArrayList<>();
		imgUrls.add("http://img4.hqbcdn.com/product/79/f3/79f3ef1b0b2283def1f01e12f21606d4.jpg");
		imgUrls.add("http://img14.hqbcdn.com/product/77/6c/776c63e6098f05fdc5639adc96d8d6ea.jpg");
		imgUrls.add("http://img13.hqbcdn.com/product/41/ca/41cad5139371e4eb1ce095e5f6224f4d.jpg");
		imgUrls.add("http://img10.hqbcdn.com/product/fa/ab/faab98caca326949b87b770c8080e6cf.jpg");
		imgUrls.add("http://img2.hqbcdn.com/product/6b/b8/6bb86086397a8cd0525c449f29abfaff.jpg");

		//初始化商品图片轮播
		vp_item_goods_img.setPages(new CBViewHolderCreator() {
									   @Override
									   public Holder createHolder(View itemView) {
										   return new NetworkImageHolderView(itemView);
									   }

									   @Override
									   public int getLayoutId() {
										   return R.layout.item_recommend_goods_item;
									   }
								   }
				, imgUrls);
	}

	@Override
	public void showLoading() {

	}

	@Override
	public void hideLoading() {

	}

	@Override
	public void onError(Throwable throwable) {

	}

	@Override
	public void goodsCommit() {

	}

	@Override
	public void goodsInfo(GoodsInforBean.DataBean.GoodsInfoBean bean) {

	}

//	@Override
//	public void goodsSpecs(List<GoodsInforBean.DataBean.GoodsInfoBean.SpecDataBean.SpecAttrBean> standardsList, List<GoodsInforBean.DataBean.GoodsInfoBean.SpecDataBean.SpecListBean> standardsInfo, List<GoodsInforBean.DataBean.GoodsInfoBean.SpecBeanX> productStandardslist) {
//
//	}



	@Override
	public void banner(List<String> urlList) {

	}

	@Override
	public void p2v(GoodsInfoDetail2 bean2) {

	}

	@Override
	public void addCarMsgCallBack(String msg) {

	}

	@Override
	public void secondFloorFragment() {

	}

	/**
	 * banner加载网络图片
	 */
	public class NetworkImageHolderView extends Holder<String> {
		private ImageView imgeView;

		public NetworkImageHolderView(View itemView) {
			super(itemView);
		}

		@Override
		protected void initView(View itemView) {
			imgeView = itemView.findViewById(R.id.sdv_goods);
		}

		@Override
		public void updateUI(String data) {
			Log.d("zwk", data + "网址");
			Glide.with(activity).load(data).listener(new RequestListener<Drawable>() {
				@Override
				public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
					Log.d("zwk", "zwkonException: " + e.toString() + "  model:" + model + " isFirstResource: " + isFirstResource);
					return false;
				}

				@Override
				public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
					Log.e("zwk", "model:" + model + " isFirstResource: " + isFirstResource);
					return false;
				}
			}).into(imgeView);
		}
	}


	@Override
	public void onStatucChanged(SlideDetailsLayout.Status status) {
		if (status == SlideDetailsLayout.Status.OPEN) {
			//当前为图文详情页
			fab_up_slide.show();
			activity.vpContent.setNoScroll(true);
			activity.tvTitle.setVisibility(View.VISIBLE);
			activity.pstsTabs.setVisibility(View.GONE);
		} else {
			//当前为商品详情页
			fab_up_slide.hide();
			activity.vpContent.setNoScroll(false);
			activity.tvTitle.setVisibility(View.GONE);
			activity.pstsTabs.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 滑动游标
	 */
	private void scrollCursor() {
		TranslateAnimation anim = new TranslateAnimation(fromX, nowIndex * v_tab_cursor.getWidth(), 0, 0);
		anim.setFillAfter(true);//设置动画结束时停在动画结束的位置
		anim.setDuration(50);
		//保存动画结束时游标的位置,作为下次滑动的起点
		fromX = nowIndex * v_tab_cursor.getWidth();
		v_tab_cursor.startAnimation(anim);

		//设置Tab切换颜色
		for (int i = 0; i < tabTextList.size(); i++) {
			tabTextList.get(i).setTextColor(i == nowIndex ? getResources().getColor(R.color.text_red) : getResources().getColor(R.color.text_black));
		}
	}

	/**
	 * 切换Fragment
	 * <p>(hide、show、add)
	 *
	 * @param fromFragment
	 * @param toFragment
	 */
	private void switchFragment(Fragment fromFragment, Fragment toFragment) {
		if (nowFragment != toFragment) {
			fragmentTransaction = fragmentManager.beginTransaction();
			if (!toFragment.isAdded()) {    // 先判断是否被add过
				fragmentTransaction.hide(fromFragment).add(R.id.fl_content, toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到activity中
			} else {
				fragmentTransaction.hide(fromFragment).show(toFragment).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
			}
		}
	}

	/**
	 * 处理推荐商品数据(每两个分为一组)
	 *
	 * @param data
	 * @return
	 */
	public static List<List<RecommendGoodsBean>> handleRecommendGoods(List<RecommendGoodsBean> data) {
		List<List<RecommendGoodsBean>> handleData = new ArrayList<>();
		int length = data.size() / 2;
		if (data.size() % 2 != 0) {
			length = data.size() / 2 + 1;
		}
		for (int i = 0; i < length; i++) {
			List<RecommendGoodsBean> recommendGoods = new ArrayList<>();
			for (int j = 0; j < (i * 2 + j == data.size() ? 1 : 2); j++) {
				recommendGoods.add(data.get(i * 2 + j));
			}
			handleData.add(recommendGoods);
		}
		return handleData;
	}
}
